package com.caigp.cookbook2.activity;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.caigp.cookbook2.R;
import com.caigp.cookbook2.adapter.FavoriteAdapter;
import com.caigp.cookbook2.base.BaseActivity;
import com.caigp.cookbook2.bean.Favorite;
import com.chad.library.adapter.base.BaseQuickAdapter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;

public class FavoriteActivity extends BaseActivity {

    @BindView(R.id.favorite_recycler_view)
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);
        setActionBarTitle("我的收藏");
        ButterKnife.bind(this);
        initRecyclerView();
    }

    @Override
    protected boolean showHomeAsUp() {
        return true;
    }

    private void initRecyclerView() {
        final List<Favorite> favoriteList = findFavorite();
        GridLayoutManager glm = new GridLayoutManager(this, 2);
        FavoriteAdapter favoriteAdapter = new FavoriteAdapter(R.layout.item_favorite, favoriteList);
        favoriteAdapter.bindToRecyclerView(recyclerView);
        favoriteAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.item_empty, null));
        favoriteAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Favorite favorite = favoriteList.get(position);
                Intent intent = new Intent(FavoriteActivity.this, DetailActivity.class);
                intent.putExtra("name", favorite.getName());
                intent.putExtra("id", favorite.getIid());
                startActivity(intent);
            }
        });
        favoriteAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                Favorite favorite = favoriteList.get(position);
                favoriteList.remove(position);
                adapter.notifyDataSetChanged();
                boolean result = deleteFavorite(String.valueOf(favorite.getIid()));
                if (result) {
                    Toast.makeText(FavoriteActivity.this, "移除成功", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
        recyclerView.setLayoutManager(glm);
        recyclerView.setAdapter(favoriteAdapter);
    }

}
